package com.qianfeng.gl4study.youshare.fragments;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.qianfeng.gl4study.youshare.R;
import com.qianfeng.gl4study.youshare.acitivity.store.PlatformProductInfoActivity;
import com.qianfeng.gl4study.youshare.acitivity.store.SubCategoryActivity;
import com.qianfeng.gl4study.youshare.adapters.StorePlatformAdapter;
import com.qianfeng.gl4study.youshare.model.Category;
import com.qianfeng.gl4study.youshare.model.Product;
import com.qianfeng.gl4study.youshare.tasks.ProductListTask;
import com.qianfeng.gl4study.youshare.tasks.TaskProcessor;
import com.qianfeng.gl4study.youshare.utils.Constants;
import com.qianfeng.gl4study.youshare.view.DataStorage;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * 平台产品显示界面
 * Created with IntelliJ IDEA.
 * I'm glad to share my knowledge with you all.
 * User:Gaolei
 * Date:2015/2/5
 * Email:pdsfgl@live.com
 */
public class StorePlatformFragment extends Fragment implements TaskProcessor, AdapterView.OnItemClickListener {
	//设置分类每行显示的数量
	public static final int NUM_COLUMN = 3;
	private boolean hasFirstLoade = false;
	private LinkedList<Product> products;
	private StorePlatformAdapter adapter;

	//获取子分类的ID，若没有指定，则认为显示平台商品的分类，否则显示相应的子分类内容，就不显示分类九宫格了。
	private String categoryId;

	public StorePlatformFragment() {

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		products = new LinkedList<Product>();
		Bundle arguments = getArguments();
		if(arguments!=null){
			categoryId = arguments.getString(Constants.ARG_SUB_CATEGORY_ID);
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_store_platform, container, false);
		//商品部分九宫格===================================
		GridView gridViewProduct = (GridView) view.findViewById(R.id.store_platform_products);
		if(gridViewProduct!=null){

			adapter = new StorePlatformAdapter(getActivity(), products);
			gridViewProduct.setAdapter(adapter);

			final LinkedList<Product> pro = products;

			/*
			单击平台商品进入商品详情
			 */
			gridViewProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
					Product product = pro.get(i);
					Intent intent = new Intent(getActivity(), PlatformProductInfoActivity.class);
					intent.putExtra("product",product);
					startActivity(intent);
					getActivity().finish();
				}
			});
		}


		//分类部分九宫格=====================================

		GridView gridViewCategory = (GridView) view.findViewById(R.id.store_platform_categories);

		if(categoryId != null){
			gridViewCategory.setVisibility(View.GONE);
		}else {

			List<Map<String ,Object>> data = new LinkedList<Map<String, Object>>();
			DataStorage dataStorage = DataStorage.getInstance();
			//获取id为2的分类：平台产品
			Category category = dataStorage.getCategory("2");
			if(category!=null){
				List<Category> subCategories = category.getSubCategories();
				gridViewCategory.setNumColumns(NUM_COLUMN);

				//设置显示整行
				int size = subCategories.size();
				int row = size / NUM_COLUMN;
				int cc = size % NUM_COLUMN;
				int realCount = 0;
				if(row>0){
					realCount = row * NUM_COLUMN;
				}
				if(subCategories!=null){
					for(Category category1:subCategories){
						String name = category1.getName();
						HashMap<String ,Object> map = new HashMap<String, Object>();
						map.put("title",name);
						//map.put("icon",R.drawable.platform_product);
						data.add(map);

						realCount--;
						if(realCount<=0){
							break;
						}
					}
				}
			}

			/**
			 * 注意：分类信息没有图片，故使用本地图片进行设置,使用SimpleAdapter
			 */
			SimpleAdapter categoryAdapter = new SimpleAdapter(
					getActivity(),
					data,
					R.layout.item_platform_category,
					new String[]{"title"},
					new int[]{R.id.item_category_title}

			);

			gridViewCategory.setAdapter(categoryAdapter);
			gridViewCategory.setOnItemClickListener(this);
		}

		String cid = "2";
		if(!hasFirstLoade){
			ProductListTask task = new ProductListTask(this);
			if(categoryId!=null){
				cid = categoryId;
			}
			task.execute(cid,"10");
		}
		return view;
	}

	//点击商品分类
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		int parentId = parent.getId();
		if(parentId == R.id.store_platform_categories){
			DataStorage dataStorage = DataStorage.getInstance();
			Category category = dataStorage.getCategory("2");
			if(category!=null){
				List<Category> subCategories = category.getSubCategories();

				//取子分类
				Category cat = subCategories.get(position);
				String catId = cat.getId();
				Intent intent = new Intent(getActivity(), SubCategoryActivity.class);
				intent.putExtra(Constants.INTENT_KEY_CSTEGOTY_ID,catId);
				startActivity(intent);
				getActivity().finish();
			}
		}

	}
	@Override
	public void processResult(JSONObject result, int flag) {
		hasFirstLoade = true;
		try {
			int code = result.getInt("code");
			//code为1，代表返回数据正确，msg是一个对象，若code不是1，代表数据请求失败，msg返回字符串
			if(code == 1){
				//数据正确，需要解析
				JSONObject msg = result.getJSONObject("msg");
				JSONObject data = msg.getJSONObject("data");
				Iterator iterator = data.keys();
				List<Product> productList = new LinkedList<Product>();
				while (iterator.hasNext()){
					Object key = iterator.next();
					JSONObject object = data.getJSONObject((String) key);
					Product product = new Product();
					product.parseJSON(object);
					productList.add(product);
				}
				//如果刷新数据，那么products需要清空，然后使用productList里面的内容添加到products，即：重新加载
				//如果实现加载更多，那么就不需清空，可以直接添加
				products.addAll(productList);
				adapter.notifyDataSetChanged();

			}else {
				//数据请求失败
				String msg = result.getString("msg");
				Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}


}